package com.wbf.demo.security;

import com.wbf.demo.service.LoginService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @program: security_demo
 * @description: 登陆业务处理器
 * @author: guangdao
 * @create: 2022-04-14 18:45
 **/
public class DefaultAuthenticationProvider implements AuthenticationProvider {
    private final LoginService loginService;

    public DefaultAuthenticationProvider(LoginService loginService) {
        if (loginService == null){
            throw new NullPointerException();
        }
        this.loginService = loginService;
    }

    @Override
    public Authentication authenticate(Authentication token) throws AuthenticationException {
        if (UserNamePassWordRegisterToken.class.equals(token.getClass())){
            return authenticate((UserNamePassWordRegisterToken) token);
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        if (UserNamePassWordRegisterToken.class.equals(clazz))
            return true;
        return false;
    }

    /**
     * 用户名密码登录
     * @param token
     * @return
     * @throws AuthenticationException
     */
    private UsernamePasswordAuthenticationToken authenticate(UserNamePassWordRegisterToken token) throws AuthenticationException {
        UserDetails user = loginService.loadUserByUsername(token.getName(), token.getCredentials().toString());
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        return auth;
    }

}